package com.example.finance_manager.dao;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.finance_manager.db.SQLiteHelper;
import com.example.finance_manager.models.Salary;

import java.util.ArrayList;
import java.util.List;

public class SalaryDao {
    private SQLiteHelper sqLiteHelper;
    private SQLiteDatabase db;

    public SalaryDao(Context context) {
        sqLiteHelper = new SQLiteHelper(context);
    }

//    增加
    public long add(Salary salary) {
        db = sqLiteHelper.getWritableDatabase();
        ContentValues cv = getContentView(salary);
        return db.insert("salary", null, cv);
    }

    public int deleteById(Integer id) {
        db = sqLiteHelper.getWritableDatabase();
        return db.delete("salary", "id = ?", new String[]{id.toString()});
    }

    public int update(Salary salary) {
        Integer id = (Integer) salary.getId();
        db = sqLiteHelper.getWritableDatabase();
        ContentValues cv = getContentView(salary);
        return db.update("salary", cv, "id = ?", new String[]{id.toString()});
    }

    public List<Salary> findAll() {
        List<Salary> list = new ArrayList<Salary>();
        db = sqLiteHelper.getReadableDatabase();
        Cursor cursor = db.query("salary", new String[]{"id", "time", "pay", "type", "other", "money"}, null, null, null, null, null);
        while (cursor.moveToNext()) {
            Salary salary = new Salary();
            salary.setId(cursor.getInt(0));
            salary.setTime(cursor.getString(1));
            salary.setPay(cursor.getString(2));
            salary.setType(cursor.getString(3));
            salary.setOther(cursor.getString(4));
            salary.setMoney(cursor.getDouble(5));
            list.add(salary);
        }
        return list;
    }

    private ContentValues getContentView(Salary salary) {
        ContentValues cv = new ContentValues();
        cv.put("time", salary.getTime());
        cv.put("pay", salary.getPay());
        cv.put("type", salary.getType());
        cv.put("other", salary.getOther());
        cv.put("money", salary.getMoney());
        return cv;
    }
}
